import React, { Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
const Business = React.lazy(() => import("../views/business"));
const Login = React.lazy(() => import("../views/login"));
const MainLayout = React.lazy(() => import("../views/mainLayout"));
const SourcesViews = React.lazy(() => import("../views/sourcesViews"));

const router_list = [
  {
    path: "/login",
    element: <Login></Login>,
  },
  {
    path: "/business",
    element: (
      <MainLayout>
        <Business></Business>
      </MainLayout>
    ),
    roles: ["admin"],
  },
  {
    path: "/sourcesViews",
    element: (
      <MainLayout>
        <SourcesViews></SourcesViews>
      </MainLayout>
    ),
  },
];

const BeforeEach: React.FC<{ element: JSX.Element; roles?: string[] }> = ({
  element, roles
}) => {
	const role = localStorage.getItem('role') || ''
	if(!roles) return element
	else if(roles.includes(role)) return element
	else return <div>403 没有权限访问</div>
}; 	

const renderRouterList = (routes: any[]) => {
  return routes.map((v) => {
    return (
      <Route
        path={v.path}
        element={<BeforeEach element={v.element} roles={v.roles}></BeforeEach>}
      ></Route>
    );
  });
};

const Router = () => {
  return (
    <BrowserRouter>
      <Suspense>
        <Routes>{renderRouterList(router_list)}</Routes>
      </Suspense>
    </BrowserRouter>
  );
};

export default Router;
